package net.yuyoo.uusession.core;

import net.spy.memcached.AddrUtil;
import net.spy.memcached.ConnectionFactory;
import net.spy.memcached.DefaultConnectionFactory;
import net.spy.memcached.MemcachedClient;
import net.yuyoo.uusession.support.HashUtil;
import net.yuyoo.uusession.support.SeqUUIDUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * memcached客户端代理
 * @author yuyoo (yuyoo4j@163.com)
 * @teme 2010-6-5 上午04:03:19
 */
public final class MemcachedClientProxy {
	
	private static Logger log = LoggerFactory.getLogger(MemcachedClientProxy.class);
	
	private static ConnectionFactory fac = new DefaultConnectionFactory();
	
	/**
	 * Memcached端点信息
	 */
	private String endpoints = null;
	
	/**
	 * spy Memcached客户端
	 */
	private MemcachedClient client = null;
	 	
	/**
	 * 构造方法
	 * @param endpoints -- Memcached连接串
	 */
	public MemcachedClientProxy(String endpoints) {
		 
		this.endpoints = endpoints;
		try {
			this.client = new MemcachedClient(fac, AddrUtil.getAddresses(endpoints));
		} catch (Exception ex) {
			throw new RuntimeException("创建Memcached客户端异常", ex);
		}
	}

	public String getEndpoints() {
		return endpoints;
	}
	
	public void setEndpoints(String endpoints) {
		this.endpoints = endpoints;
	}
	
	public Object get(String key) { 
		
		long hash = HashUtil.getDJBHash(key);
		String k = SeqUUIDUtil.BaseConvert.compressNumber(hash, 6);
		log.debug("GET compress: [{}]->[{}]", key, k);
		return client.get(k);
	}
	
	public void set(String key, Object val) {

		long hash = HashUtil.getDJBHash(key);
		String k = SeqUUIDUtil.BaseConvert.compressNumber(hash, 6);
		log.debug("SET compress: [{}]->[{}]", key, k);
		client.set(k, 0, val);
	}
	
	public void set(String key, Object val, long expiry) {

		long hash = HashUtil.getDJBHash(key);
		String k = SeqUUIDUtil.BaseConvert.compressNumber(hash, 6);
		log.debug("SET compress: [{}]->[{}]", key, k);
		client.set(k, (int)(expiry / 1000), val);
	}
	
	public void delete(String key) {

		long hash = HashUtil.getDJBHash(key);
		String k = SeqUUIDUtil.BaseConvert.compressNumber(hash, 6);
		log.debug("DELETE compress: [{}]->[{}]", key, k);
		client.delete(k);
	}
	
	@Override
	public String toString() {

		StringBuilder sb = new StringBuilder();
		sb.append("MemcachedClientProxy{");
		sb.append(" endpoints:").append(endpoints);
		sb.append("}");
		return sb.toString();
	}
}
